package com.example.demospringboot.flow.converter;

import com.example.demospringboot.flow.listener.MyTaskListener;
import com.fasterxml.jackson.databind.JsonNode;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.FlowableListener;
import org.flowable.bpmn.model.ImplementationType;
import org.flowable.bpmn.model.UserTask;
import org.flowable.editor.language.json.converter.BpmnJsonConverterContext;
import org.flowable.editor.language.json.converter.UserTaskJsonConverter;
import org.flowable.engine.delegate.TaskListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhaoPin
 * @Date 2024/8/23  14:39
 * @description: 自定义解析 UserTask
 */
public class LocalUserTaskJsonConverter extends UserTaskJsonConverter {

    @Override
    protected FlowElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap,
                                               BpmnJsonConverterContext converterContext) {
        FlowElement task =  super.convertJsonToElement(elementNode, modelNode, shapeMap, converterContext);

        // 自定义属性解析
        convertJsonToProperties(elementNode,task);

        // 解析自定义的属性监听器
        UserTask userTask = (UserTask)task;
        FlowableListener listener = new FlowableListener();
        listener.setEvent( TaskListener.EVENTNAME_CREATE);
        listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_INSTANCE);

        // 自定义的listener
        TaskListener taskListener = new MyTaskListener();

        listener.setInstance(taskListener);
        userTask.getTaskListeners().add(listener);

        return task;

    }

    /**
     * 自定义属性解析
     *
     * @param objectNode
     * @param element
     */
    protected void convertJsonToProperties(JsonNode objectNode, BaseElement element) {

        JsonNode formPropertiesNode = getProperty("zpName", objectNode);
        if (formPropertiesNode != null) {
            List<ExtensionElement> list = new ArrayList<>();
            ExtensionElement extensionElement = new ExtensionElement();
            extensionElement.setName("zpName");
            extensionElement.setElementText("一切自定义的内容");
            list.add(extensionElement);

            ((UserTask) element).getExtensionElements().put("zpName",list);
        }
    }



}
